import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  setToken,
  removeToken,
  setUserInfo,
  removeUserInfo,
} from '@/utils/auth'
import { request } from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref(null)

  // 登录
  const login = async (username: string, password: string) => {
    try {
      const { token: accessToken } = await request.post('/auth/login', {
        username,
        password,
      })
      token.value = accessToken
      setToken(accessToken)
      return true
    } catch (error) {
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const data = await request.get('/user/info')
      userInfo.value = data
      setUserInfo(data)
      return data
    } catch (error) {
      return null
    }
  }

  // 登出
  const logout = async () => {
    try {
      await request.post('/auth/logout')
    } finally {
      token.value = ''
      userInfo.value = null
      removeToken()
      removeUserInfo()
    }
  }

  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout,
  }
})
